import React from 'react'
// import Api from 'Utils/api';
import { API_HOST } from 'Constants/config';
import './index.scss'

class UploadVideo extends React.PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      id: '',
      src: '',
      progress: 0,
    }
  }
  getId(e) {
    if (e.currentTarget.status === 200 && e.currentTarget.readyState === 4) {
      this.setState({
        id: JSON.parse(e.currentTarget.responseText).id,
        src: `${API_HOST}/files/mobile/${JSON.parse(e.currentTarget.responseText).id}`,
      }, () => { this.setState({ progress: 100 }); this.props.uploadHandle(this.state.id) });
    }
  }
  clearSrc() {
    this.setState({
      src: '',
    })
  }
  uploadProgress(evt) {
    const percentComplete = Math.round((evt.loaded * 99) / evt.total);
    this.setState({
      progress: percentComplete,
    });
  }
  fileSelected() {
    const file = document.getElementById('fileToUpload').files[0];
    const formData = new FormData();
    formData.append('upload_file', file, file.name);
    const xhr = new window.XMLHttpRequest();
    xhr.upload.addEventListener('progress', this.uploadProgress.bind(this), false);
    xhr.onreadystatechange = this.getId.bind(this);
    xhr.open('POST', `${API_HOST}/files`);
    xhr.send(formData)
  }
  render() {
    return (
      <div>
        <div className="media">
          <div className="upload">
            <img src="./images/media/icon_photograph.png" alt="摄影" className="" />
            <input type="file" accept="video/*" onChange={this.fileSelected.bind(this)} id="fileToUpload"></input>
          </div>
        </div>
        {
          (this.state.progress !== 0 && this.state.progress !== 100) &&
          <div className="progress-container">
            <div className="progress-inner" style={{ width: `${this.state.progress}%` }}></div>
          </div>
        }
        <div className="photo-container" style={{ display: 'flex' }}>
          {
            this.state.src &&
            <video
              id="video"
              src={this.state.src}
              controls="controls"
              ref={(ref) => {
                this.video = ref;
              }}
            >
            </video>
          }
        </div>
      </div>
    )
  }
}
export default UploadVideo
